package controller

import (
	"context"
	"fmt"
	"parking-lot-go-push/controller/parknfly"
	"parking-lot-go-push/controller/xiaoqiang"
	"parking-lot-go-push/logger"
	"parking-lot-go-push/model"
	"parking-lot-go-push/model/cars"
	"parking-lot-go-push/mongodb"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var entryLogger = logger.NewLogger("entry", "error")

func Entry() {

	//tag查询
	ctx := context.TODO()
	var entryStruct mongodb.CarsEntryMongoDbStruct

	collection := model.MongoDb.Collection(entryStruct.MongoDBTableName())
	cur, err := collection.Find(ctx, bson.M{
		"push_status": 0,
		"push_err_num": bson.M{
			"$lt": 5,
		},
		"push_time": bson.M{
			"$lte": time.Now().Unix(),
		},
	}, options.Find().SetSort(bson.D{{"in_time", 1}}))
	if err != nil {
		entryLogger.Error(fmt.Sprintf("入场记录查询失败:%s", err.Error()))
		return
	}
	defer cur.Close(ctx)

	var entryData []mongodb.CarsEntryMongoDbStruct

	for cur.Next(ctx) {
		var entry mongodb.CarsEntryMongoDbStruct
		if err := cur.Decode(&entry); err != nil {
			entryLogger.Error(fmt.Sprintf("标签:解码入场数据失败:%s", err.Error()))
			return
		}
		entryData = append(entryData, entry)
	}

	if len(entryData) == 0 {
		entryLogger.Info("没有需要处理的数据")
	}

	for _, v := range entryData {
		entryLogger.Info(fmt.Sprintf("推送车牌:%s,订单类型:%d", v.CarNumber, v.OrderType))

		switch v.OrderType {
		case 1: //小强
			var xiaoQiangEntry xiaoqiang.EntryStruct
			xiaoQiangEntry.CarsEntryMongoDbStruct = v
			xiaoQiangEntry.Entry()
		case 2: //泊安飞
			var parknflyEntry parknfly.EntryStruct
			parknflyEntry.CarsEntryMongoDbStruct = v
			parknflyEntry.Entry()
		case 3: //钉钉
			if err := CurlPostJson("push/entry", map[string]interface{}{
				"park_name":    v.ParkName,
				"car_number":   v.CarNumber,
				"car_no_color": v.CarNoColor,
				"region_name":  v.RegionName,
				"in_time":      v.InTime,
			}); err != nil {
				entryLogger.Info(fmt.Sprintf("钉钉进场推送失败,车牌:%s,颜色:%d", v.CarNumber, v.CarNoColor))
			} else {
				var carsEntryStruct cars.CarsEntryStruct
				if err := carsEntryStruct.PushSuccess(v.OrderNo, v.InTime, v.ParkCode, v.OrderType, 0); err != nil {
					entryLogger.Info(fmt.Sprintf("钉钉更新订单状态失败,车牌:%s,颜色:%d", v.CarNumber, v.CarNoColor))
				}
			}
		}
	}

}
